import mockjs from 'mockjs';
import { delay } from 'roadhog-api-doc';
import { parse } from 'url';
import { pagination } from '@/utils/utils'

// *****************************************************************************************
// * 登陆、退出登录、获得当前登陆用户信息
// *****************************************************************************************
let currentToken = undefined;

function login(req, res, u, b) {
  const body = (b && b.body) || req.body;
  const { username, password } = body;
  if (username === 'error') {
    console.log('Mock: error username');
    return res.status(200).json({ code: 400, message: 'error username' });
  }
  if (password === 'error') {
    console.log('Mock: error password');
    return res.status(200).json({ code: 400, message: 'error password' });
  }
  // 生成token
  currentToken = '439ab67e93ff4ad688424de1bce7b8b1';
  console.log('Mock: login successfully');
  return res.status(200).json({
    code: 200,
    message: 'login successfully',
    data: {
      token: currentToken,
      user: getUserByToken(currentToken),
      right: getUserRightByToken(currentToken),
    }
  });
}

function logout(req, res, u, b) {
  const body = (b && b.body) || req.body;
  const { token } = body;

  currentToken = undefined;
  console.log('Mock: logout successfully token ' + token);
  return res.status(200).json({
    code: 200,
    message: 'logout successfully',
  });
}

let loginExpire = false;

function getByToken(req, res, u, b) {
  let token = req.params.token;
  if (token && token === currentToken) {
    if (!loginExpire) {
      console.log('Mock: get current by token ' + token);
      return res.status(200).json({
        code: 200,
        message: 'successfully',
        data: {
          token: token,
          user: getUserByToken(token),
          right: getUserRightByToken(token),
        }
      });
    } else {
      console.log('Mock: expired token ' + token);
      return res.status(200).json({
        code: 400,
        message: 'token expired',
      });
    }
  } else {
    console.log('Mock: invalid token ' + token);
    return res.status(200).json({
      code: 400,
      message: 'token invalid',
    });
  }
}

function getUserByToken(token) {
  console.log('Mock: get user by token ' + token);
  return {
    id: 1,
    username: `admin`,
    password: null,
    phone: '1388888888',
    email: 'zs@123.com',
    status: 1,
    created: new Date(`2019-03-18`),
    updated: new Date(`2019-03-18`),
  };
}

function getUserRightByToken(token) {
  console.log('Mock: get right by token ' + token);
  return roleRight;
}

// *****************************************************************************************
// * 用户管理
// *****************************************************************************************
let userList = [];
for (let i = 0; i < 46; i += 1) {
  userList.push({
    id: i,
    username: `张三${i}`,
    password: null,
    phone: '1388888888' + (i % 10),
    email: 'zs' + i + '@123.com',
    status: i % 2,
    created: new Date(`2019-03-${Math.floor(i / 2) + 1}`),
    updated: new Date(`2019-03-${Math.floor(i / 2) + 1}`),
  });
}

function getUser(req, res, u) {
  let url = u;
  if (!url || Object.prototype.toString.call(url) !== '[object String]') {
    url = req.url; // eslint-disable-line
  }
  const params = parse(url, true).query;

  let dataSource = userList;

  if (params.sorter) {
    const s = params.sorter.split('_');
    dataSource = dataSource.sort((prev, next) => {
      if (s[1] === 'descend') {
        return next[s[0]] - prev[s[0]];
      }
      return prev[s[0]] - next[s[0]];
    });
  }

  if (params.status) {
    const status = params.status.split(',');
    let filterDataSource = [];
    status.forEach(s => {
      filterDataSource = filterDataSource.concat(
        dataSource.filter(data => parseInt(data.status, 10) === parseInt(s[0], 10))
      );
    });
    dataSource = filterDataSource;
  }

  if (params.username) {
    dataSource = dataSource.filter(data => data.username.indexOf(params.username) > -1);
  }

  if (params.phone) {
    dataSource = dataSource.filter(data => data.phone.indexOf(params.phone) > -1);
  }

  if (params.email) {
    dataSource = dataSource.filter(data => data.email.indexOf(params.email) > -1);
  }

  if (params.createdSt && params.createdEd) {
    dataSource = dataSource.filter(
      data => data.created >= params.createdSt && data.created <= params.createdEd
    );
  }

  let pageSize = 10;
  if (params.pageSize) {
    pageSize = params.pageSize * 1;
  }

  const result = {
    list: pagination(parseInt(params.currentPage, 10) || 1, pageSize, dataSource),
    pagination: {
      total: dataSource.length,
      pageSize,
      current: parseInt(params.currentPage, 10) || 1,
    },
  };

  console.log('Mock: got users');
  return res.status(200).json({
    code: 200,
    data: result,
  });
}

function getUserById(req, res) {
  let id = req.params.id;
  let user =
    userList.filter(item => parseInt(item.id, 10) === parseInt(id, 10)) &&
    userList.filter(item => parseInt(item.id, 10) === parseInt(id, 10))[0];
  return res.status(200).json({
    code: 200,
    data: user,
  });
}

function addUser(req, res, u, b) {
  const body = (b && b.body) || req.body;
  const { username, phone, email, status } = body;

  const i = Math.ceil(Math.random() * 10000);
  userList.unshift({
    id: i,
    username: username,
    password: null,
    phone: phone,
    email: email,
    status: status,
    created: new Date(),
    updated: new Date(),
  });
  console.log('Mock: user added');
  return res.status(200).json({
    code: 200,
    message: 'User added',
  });
}

function updateUser(req, res, u, b) {
  const body = (b && b.body) || req.body;
  const { id, username, phone, email, status } = body;

  userList.forEach(item => {
    if (parseInt(item.id, 10) === parseInt(id, 10)) {
      item = Object.assign(item, {
        username: username || item.username,
        phone: phone || item.phone,
        email: email || item.email,
        status: status || item.status,
        updated: new Date(),
      });
    }
  });
  console.log('Mock: user updated');
  return res.status(200).json({
    code: 200,
    message: 'User updated',
  });
}

function resetPwd(req, res, u, b) {
  const body = (b && b.body) || req.body;
  const { ids } = body;

  ids.forEach(id => {
    userList.forEach(item => {
      if (parseInt(item.id, 10) === parseInt(id, 10)) {
        item = Object.assign(item, {
          password: 888888,
          updated: new Date(),
        });
      }
    });
  });
  console.log('Mock: pwds reset');
  return res.status(200).json({
    code: 200,
    message: 'Password reset',
  });
}

function disableUser(req, res, u, b) {
  const body = (b && b.body) || req.body;
  const { ids } = body;

  ids.forEach(id => {
    userList.forEach(item => {
      if (parseInt(item.id, 10) === parseInt(id, 10) && parseInt(item.status, 10) === 1) {
        item = Object.assign(item, {
          status: 0,
          updated: new Date(),
        });
      }
    });
  });
  console.log('Mock: user disabled');
  return res.status(200).json({
    code: 200,
    message: 'User disabled',
  });
}

function deleteUsers(req, res, u, b) {
  const body = (b && b.body) || req.body;
  const { ids } = body;

  userList = userList.filter(item => ids.indexOf(parseInt(item.id, 10)) < 0);
  console.log('Mock: users deleted');
  return res.status(200).json({ code: 200, message: 'users deleted' });
}

function deleteUser(req, res, u) {
  let id = req.params.id;
  userList = userList.filter(item => parseInt(item.id, 10) !== parseInt(id, 10));
  console.log('Mock: user deleted');
  return res.status(200).json({ code: 200, message: 'deleted' });
}

// *****************************************************************************************
// * 角色管理
// *****************************************************************************************
let roleList = [];
for (let i = 0; i < 22; i += 1) {
  roleList.push({
    id: i,
    name: `角色${i}`,
    roleDesc: `角色${i}用于角色${i}`,
    created: new Date(`2019-03-${Math.floor(i / 2) + 1}`),
    updated: new Date(`2019-03-${Math.floor(i / 2) + 1}`),
  });
}

function getRole(req, res, u) {
  let url = u;
  if (!url || Object.prototype.toString.call(url) !== '[object String]') {
    url = req.url; // eslint-disable-line
  }
  const params = parse(url, true).query;

  let dataSource = roleList;

  if (params.sorter) {
    const s = params.sorter.split('_');
    dataSource = dataSource.sort((prev, next) => {
      if (s[1] === 'descend') {
        return next[s[0]] - prev[s[0]];
      }
      return prev[s[0]] - next[s[0]];
    });
  }

  let pageSize = 10;
  if (params.pageSize) {
    pageSize = params.pageSize * 1;
  }

  const result = {
    list: pagination(parseInt(params.currentPage, 10) || 1, pageSize, dataSource),
    pagination: {
      total: dataSource.length,
      pageSize,
      current: parseInt(params.currentPage, 10) || 1,
    },
  };

  console.log('Mock: got roles');
  return res.status(200).json({
    code: 200,
    data: result,
  });
}

let userRole = [3, 5, 6];

function getUserRole(req, res, u) {
  let userId = req.params.id;

  console.log('Mock: got roles of user ' + userId);
  return res.status(200).json({
    code: 200,
    data: userRole,
  });
}

function setUserRole(req, res, u, b) {
  let userId = req.params.id;
  const body = (b && b.body) || req.body;
  const { roleIds } = body;

  userRole = roleIds;
  console.log('Mock: roles of user ' + userId + ' set');
  return res.status(200).json({ code: 200, message: 'roles set' });
}

function addRole(req, res, u, b) {
  const body = (b && b.body) || req.body;
  const { name, roleDesc } = body;

  const i = Math.ceil(Math.random() * 10000);
  roleList.unshift({
    id: i,
    name: name,
    roleDesc: roleDesc,
    created: new Date(),
    updated: new Date(),
  });
  console.log('Mock: role added');
  return res.status(200).json({ code: 200, message: 'role added' });
}

function updateRole(req, res, u, b) {
  const body = (b && b.body) || req.body;
  const { id, name, roleDesc } = body;

  roleList.forEach(item => {
    if (parseInt(item.id, 10) === parseInt(id, 10)) {
      item = Object.assign(item, {
        name: name || item.name,
        roleDesc: roleDesc || item.roleDesc,
        updated: new Date(),
      });
    }
  });
  console.log('Mock: role updated');
  return res.status(200).json({ code: 200, message: 'role updated' });
}

// 权限数据
let rightData = [];
rightData.unshift(
  { id: '10101', menuId: 1, type: 1, name: '查看', },// home-view

  { id: '10201', menuId: 2, type: 1, name: '查看', },// permission-view

  { id: '10301', menuId: 3, type: 1, name: '查询', },// user-view
  { id: '10302', menuId: 3, type: 2, name: '新增', },// user-add
  { id: '10303', menuId: 3, type: 3, name: '修改', },// user-update
  { id: '10311', menuId: 3, type: 5, name: '重置密码', },// user-resetpwd
  { id: '10312', menuId: 3, type: 6, name: '指定角色', },// user-roleset

  { id: '10401', menuId: 4, type: 1, name: '查询', },// role-view
  { id: '10402', menuId: 4, type: 2, name: '新增', },// role-add
  { id: '10403', menuId: 4, type: 3, name: '修改', },// role-update
  { id: '10413', menuId: 4, type: 7, name: '指定权限', },// role-rightset

  { id: '10901', menuId: 9, type: 1, name: '查看', },// log-view

  { id: '11001', menuId: 10, type: 1, name: '查询', },// login-view

  { id: '11101', menuId: 11, type: 1, name: '查询', },// operation-view

  { id: '10501', menuId: 5, type: 1, name: '查看', },// documents-view

  { id: '10601', menuId: 6, type: 1, name: '查看', },// react-view
  { id: '10701', menuId: 7, type: 1, name: '查看', },// umi-view
  { id: '10801', menuId: 8, type: 1, name: '查看', },// ant-design-view
);

function getRight(req, res, u) {
  let url = u;
  if (!url || Object.prototype.toString.call(url) !== '[object String]') {
    url = req.url; // eslint-disable-line
  }
  const params = parse(url, true).query;

  let pageSize = 10;
  if (params.pageSize) {
    pageSize = params.pageSize * 1;
  }
  const result = {
    list: pagination(parseInt(params.currentPage, 10) || 1, pageSize, rightData),
    pagination: {
      total: rightData.length,
      pageSize,
      current: parseInt(params.currentPage, 10) || 1,
    },
  };

  console.log('Mock: got rights');
  return res.status(200).json({
    code: 200,
    data: result,
  });
}

// 角色权限数据
let roleRight = [];
roleRight = rightData.map(item => item.id);

function getRoleRight(req, res, u) {
  let roleId = req.params.id;

  console.log('Mock: got rights of role ' + roleId);
  return res.status(200).json({
    code: 200,
    data: roleRight,
  });
}

function setRoleRight(req, res, u, b) {
  let roleId = req.params.id;
  const body = (b && b.body) || req.body;
  const { rightIds } = body;

  roleRight = rightIds;
  console.log('Mock: rights of role ' + roleId + ' set');
  return res.status(200).json({ code: 200, message: 'rights set' });
}

// *****************************************************************************************
// * 匹配
// *****************************************************************************************
const proxy = {
  'POST /api/us/user/login': login,
  'POST /api/us/user/logout': logout,
  'GET /api/us/user/info/:token': getByToken,

  'GET /api/us/user': getUser,
  'GET /api/us/user/:id': getUserById,
  'POST /api/us/user': addUser,
  'PUT /api/us/user': updateUser,
  'DELETE /api/us/user': deleteUsers,
  'DELETE /api/us/user/:id': deleteUser,
  'PUT /api/us/user/resetpwd': resetPwd,
  'PUT /api/us/user/disable': disableUser,

  'GET /api/us/user/:id/role': getUserRole,
  'PUT /api/us/user/:id/role': setUserRole,

  'GET /api/us/role': getRole,
  'POST /api/us/role': addRole,
  'PUT /api/us/role': updateRole,

  'GET /api/us/right': getRight,
  'GET /api/us/role/:id/right': getRoleRight,
  'PUT /api/us/role/:id/right': setRoleRight,

};

// 调用 delay 函数，统一处理
export default delay(proxy, 2000);